﻿using System.Data;
using System.Globalization;
using System.Linq;
using AkazoNobel.Scheduler.StoreMasterData.Common;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Model;
using Dapper;

namespace AkazoNobel.Scheduler.StoreMasterData.DataAccess.Service
{
    public static class SequenceService
    {
        public static string Generate(string prefix, string postfix, int digits)
        {
            prefix = prefix ?? "";
            postfix = postfix ?? "";

            Sequence seq = null;
            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var sequences = conn.Query<Sequence>(
                    "SELECT * FROM t_Sequence WHERE prefix=@prefix AND postfix=@postfix AND digits=@digits", 
                    new { prefix, postfix, digits }).ToList();
                
                if (sequences.Any())
                {
                    seq = sequences.OrderByDescending(t => t.No).First();
                    seq.No = seq.No + 1;
                }
                else
                {
                    seq = new Sequence {Prefix = prefix, Postfix = postfix, Digits = digits, No = 1};
                }

                conn.Execute("INSERT INTO t_Sequence(prefix, postfix, digits, no) VALUES(@prefix, @postfix, @digits, @no)", seq);
            }

            return prefix + seq.No.ToString().PadLeft(digits < 0 ? 0 : digits, '0') + postfix;
        }
    }
}
